package timer;

import configuration.RobConfiguration;
import http.util.PrintUtil;
import main.robClass;
import mysql.MysqlUtil;
import java.util.HashMap;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static http.util.PrintUtil.printTitle;


public class saveCoursesManager {
    /**PE: 全局课程名与课程Id*/
    /**Common: 全局课程名与课程Id*/
    /**Pe: CourseNameAndId HashMap: "04TY47":"篮球"*/
    /**Common: CourseNameAndId HashMap: ["(2021-2022-1)-02073X-071788-2","(2021-2022-1)-W0F528-T00039-1","(2021-2022-1)-06025X-061792-1"] 传入隐藏代码(hiddCode) 发包数据(postValue)*/
    public static HashMap<String, String> globalIdAndCourseNameCache = new HashMap<>();

    static {
        robClass.logger.info("saveCookieManager - 管理Cookie备份已加载");
    }

    /**根据Put方法添加课程 兼容不同学院不同课程的情况*/
    public static HashMap<String, String> getGlobalIdAndCourseNameCache() {
//        robClass.logger.info("返回数据集:" + globalIdAndCourseNameCache);
        return globalIdAndCourseNameCache;
    }
    /**加载数据的时候使用*/
    public static void setGlobalIdAndCourseNameCache(HashMap<String, String> globalIdAndCourseNameCache) {
        saveCoursesManager.globalIdAndCourseNameCache = globalIdAndCourseNameCache;
    }

    /**
     *备份课程列表线程
     *30秒备份一次
     **/
    public static void startBackupCourseList() {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        pool.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                PrintUtil.printTitle("进行抢课课表备份");
                if (globalIdAndCourseNameCache.isEmpty()) {
                    PrintUtil.printTitle("沒有需要备份的课表");
                    return;
                }
                MysqlUtil.updateCourseTables(RobConfiguration.ROB_CHANNEL.name()+"_"+RobConfiguration.ROB_COURSE_TYPE.name(), getGlobalIdAndCourseNameCache());
            }
        }, 0, 1, TimeUnit.MINUTES);
    }

    /**从数据库中获取课程列表*/
    public static void initBackupCourseList() {
        HashMap<String, String> courseList = MysqlUtil.initCourseList(RobConfiguration.ROB_CHANNEL.name()+"_"+RobConfiguration.ROB_COURSE_TYPE.name());
        if (courseList != null) {
            saveCoursesManager.setGlobalIdAndCourseNameCache(courseList);
            PrintUtil.printTitle("initBackupCourseList - 加载课表完毕");
            robClass.logger.info(getGlobalIdAndCourseNameCache());
        }
    }
    /**备份一下全局课表 作为缓存*/
    public static void saveCourseList(){
        MysqlUtil.updateCourseTables(RobConfiguration.ROB_CHANNEL.name() + "_" + RobConfiguration.ROB_COURSE_TYPE.name(), getGlobalIdAndCourseNameCache());
        printTitle("自动备份课表完毕");
    }

}